
#include<bits/stdc++.h>
using namespace std;
class Solution
{
    int dx[4]={-1,1,0,0};
    int dy[4]={0,0,-1,1};
    int ret=0;
    int path=0;
    int n,m;
    bool check[16][16];
public:
    int getMaximumGold(vector<vector<int>> &grid)
    {
        n=grid.size();
        m=grid[0].size();
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                if(grid[i][j]!=0)
                {
                    check[i][j]=true;
                    path+=grid[i][j];
                    dfs(i,j,grid);
                    check[i][j]=false;
                    path-=grid[i][j];
                }
            }
        }
        return ret;
    }

    void dfs(int i,int j,vector<vector<int>> &grid)
    {
        ret=max(ret,path);
        for(int k=0;k<4;k++)
        {
            int x=dx[k]+i;
            int y=dy[k]+j;
            if(x>=0&&x<n&&y>=0&&y<m&&check[x][y]==false&&grid[i][j])
            {
                check[x][y]=true;
                path+=grid[x][y];
                dfs(x,y,grid);
                check[x][y]=false;
                path-=grid[x][y];
            }
        }
    }
};